package socket.socket_2;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        System.out.println("等待连接服务端....");
        try {
            socket  = new Socket("localhost",8088);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("已连接服务端");
    }
    public  void start(){
        ServerHandler handler = new ServerHandler();
        Thread t = new Thread(handler);
        t.setDaemon(true);
        t.start();
        try {
            OutputStream  out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);// 需要自动刷新为true.
            Scanner sc = new Scanner(System.in);
            System.out.println("请开始输入数据，输入exit退出");
            while (true) {
                String s = sc.nextLine();
                if ("exit".equalsIgnoreCase(s)) {
                    break;
                }
                pw.println(s);
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally { // 挥手说再见
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
class ServerHandler implements Runnable{
    @Override
    public void run() {
        try {
            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String message;
            while ((message = br.readLine()) != null){
                System.out.println(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
}
